package com.ruoyi.collection.process;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.base.yaml.BusinessConfig;
import com.ruoyi.bizsys.domain.CreditAccount;
import com.ruoyi.bizsys.domain.CustBankCard;
import com.ruoyi.bizsys.domain.LoanIou;
import com.ruoyi.bizsys.domain.RepaymentOrder;
import com.ruoyi.bizsys.service.ICreditAccountService;
import com.ruoyi.bizsys.service.ICustBankCardService;
import com.ruoyi.bizsys.service.ILoanIouService;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.collection.domain.ApiParameter;
import com.ruoyi.collection.domain.CollectionRepaymentReq;
import com.ruoyi.collection.domain.CollectionRepaymentResp;
import com.ruoyi.collection.process.api.CollectionProcess;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.util.business.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 催收还款处理
 * @author Victor
 *
 */
@Slf4j
@Service("CollectionRepayment")
public class CollectionRepaymentPorcessor implements CollectionProcess {
    @Autowired
    ILoanIouService loanIouService;

    @Autowired
    private ICreditAccountService creditAccountService;

    @Autowired
    ICustBankCardService custBankCardService;

    @Autowired
    BusinessConfig businessConfig;
    private static RestTemplate restTemplate;

    static {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(180000);
        factory.setReadTimeout(180000);
        restTemplate = new RestTemplate(factory);
    }

    @Override
    public Object process(ApiParameter req) throws Exception {
        log.info("催收还款开始，{}",req.getBody().toString());
        // body加了个字段repaymentMethod，为 1 就走钱包，为2就走老的银行卡
        CollectionRepaymentReq reqBody = JSON.parseObject(req.getBody().toString(), CollectionRepaymentReq.class);
        CollectionRepaymentResp respBody = new CollectionRepaymentResp();
        respBody.setWithholdTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()));
        respBody.setRealActAmt(reqBody.getRealActAmt());
        if(reqBody.getRepaymentMethod()==1){
            log.info("催收还款开始,走钱包代扣，{}",req.getBody().toString());
            JSONObject res = getRepaymentOrder(reqBody.getContrNbr());
            log.info("催收还款开始,走钱包代扣res，{}",res.toJSONString());
            respBody.setMsg(res.getString("msg"));
            if (res.getBoolean("status")) {
                respBody.setOrderId(res.getString("repaymentOrderId"));
                respBody.setRealActAmt(res.getBigDecimal("amt"));
                respBody.setWithholdStatus("S");
            } else {
                respBody.setWithholdStatus("F");
            }
            return respBody;
        }
        //获取借据详情
        LoanIou LoanIouQuery = new LoanIou();
        LoanIouQuery.setLoanSerialNo(reqBody.getContrNbr());
        LoanIouQuery.setState(UserConstants.BUSINESS_NORMAL);
        List<LoanIou> loanList = loanIouService.selectLoanIouList(LoanIouQuery);
        if (loanList.size() != 1) {
            log.error("催收还款时借据数据异常");
            throw new Exception("借据数据异常");
        }

        //获取账户信息
        CreditAccount accountQuery = new CreditAccount();
        accountQuery.setCustNo(loanList.get(0).getCustNo());
        accountQuery.setOnLoan(BizConstants.ACCOUNT_ON_lOAN_STATUS_1);
        accountQuery.setState(UserConstants.BUSINESS_NORMAL);
        List<CreditAccount> selectCreditAccountList = creditAccountService.selectCreditAccountList(accountQuery);

        //查询还款银行卡信息
        CustBankCard bankCard = null;
        CustBankCard custBankCard = new CustBankCard();
        custBankCard.setCustNo(loanList.get(0).getCustNo());
        if (StringUtils.isNotEmpty(reqBody.getCardNumber())) {
            custBankCard.setCardNumber(reqBody.getCardNumber().replaceAll("\\*", ""));
        } else {
            custBankCard.setIsDefault("Y");
        }
        custBankCard.setState(UserConstants.BUSINESS_NORMAL);
        List<CustBankCard> custBankCardList = custBankCardService.selectCustBankCardList(custBankCard);
        if (custBankCardList.size() == 1) {
            bankCard = custBankCardList.get(0);
        }

        if (!(selectCreditAccountList.size() == 1 && null != bankCard)) {
            log.error("催收还款时核心数据异常");
            throw new Exception("核心数据异常");
        }


        RepaymentOrder resultOrder = getRepaymentOrder(reqBody.getContrNbr(),reqBody.getRealActAmt(), loanList.get(0).getId(), selectCreditAccountList.get(0).getId(), bankCard.getId());
        if (null != resultOrder) {
            // 响应赋值
            respBody.setOrderId(resultOrder.getRepaymentNo());
            if (BizConstants.REPAYMENT_ORDER_STATUS_SUCCESS == resultOrder.getRepayStatus()) {
                respBody.setWithholdStatus("S");
            } else if (BizConstants.REPAYMENT_ORDER_STATUS_DOING == resultOrder.getRepayStatus()) {
                respBody.setWithholdStatus("P");
            } else if (BizConstants.REPAYMENT_ORDER_STATUS_WAIT == resultOrder.getRepayStatus()) {
                respBody.setWithholdStatus("I");
            } else {
                respBody.setWithholdStatus("F");
            }
        }
//        //查询是否有在途的扣款
//        int hasInRepaymentCount = bRepaymentService.getInRepaymentCountByLoan(reqBody.getContrNbr());
//        if (hasInRepaymentCount > 0) {//存在在途扣款申请
//            log.info("存在在途扣款");
//            throw new Exception("存在在途扣款");
//        } else {
//            RepaymentOrder resultOrder = bLoanInfoService.doCollectionRepaymentAction(
//                    loanList.get(0), selectCreditAccountList.get(0), bankCard, reqBody.getRealActAmt());
//            if (null == resultOrder) {
//                log.error("代扣订单生成异常");
//                throw new Exception("代扣订单生成异常");
//            }// 响应赋值
//            respBody.setOrderId(resultOrder.getRepaymentNo());
//            if(BizConstants.REPAYMENT_ORDER_STATUS_SUCCESS == resultOrder.getRepayStatus()){
//                respBody.setWithholdStatus("S");
//            }else if(BizConstants.REPAYMENT_ORDER_STATUS_DOING == resultOrder.getRepayStatus()){
//                respBody.setWithholdStatus("P");
//            }else if(BizConstants.REPAYMENT_ORDER_STATUS_WAIT == resultOrder.getRepayStatus()){
//                respBody.setWithholdStatus("I");
//            }else{
//                respBody.setWithholdStatus("F");
//            }
//
//
//        } 注释于 拆分，wqg。

        log.info("催收还款结束");
        return respBody;

    }

    /**
     * 调用业务系统进行查询
     *
     * @return
     */
    private RepaymentOrder getRepaymentOrder(String contrNbr, BigDecimal realActAmt,
                                               Long loanIouId, Long createAccountId, Long bankCardId) {
        log.info("wqg:调用业务系统进行查询---");
        Map<String, Object> map = new HashMap<>();
        map.put("contrNbr",contrNbr);
        map.put("realActAmt",realActAmt);
        map.put("loanIouId",loanIouId);
        map.put("createAccountId",createAccountId);
        map.put("bankCardId",bankCardId);
        String url = businessConfig.getApiurl()+"/forcollection/collection/call?contrNbr={contrNbr}&realActAmt={realActAmt}&loanIouId={loanIouId}&createAccountId={createAccountId}&bankCardId={bankCardId}";
        RepaymentOrder resultOrder = restTemplate.getForObject(url,RepaymentOrder.class,map);
        return resultOrder;
    }

    /**
     * 调用业务系统进行查询
     *
     * @return
     */
    private JSONObject getRepaymentOrder(String loanSerialNo) {
        log.info("wqg:调用业务系统进行查询-钱包代扣--"+loanSerialNo);
        String url = businessConfig.getApiurl()+"/forcollection/collection/walletpay?loanSerialNo="+loanSerialNo;
        log.info("wqg:调用业务系统进行查询-钱包代扣-url--"+url);
        JSONObject res = restTemplate.getForObject(url,JSONObject.class,"");
        log.info("wqg:调用业务系统进行查询-钱包代扣-结果--"+res.toJSONString());
        return res;
    }

}
